package com.lovely3x.versionchecklibrary;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;

import com.lovely3x.common.CommonApplication;
import com.lovely3x.common.activities.BaseCommonActivity;
import com.lovely3x.common.requests.Config;
import com.lovely3x.common.utils.ALog;
import com.lovely3x.common.utils.BaseWeakHandler;
import com.lovely3x.common.versioncontroller.Version;

/**
 * 启动页
 * Created by lovely3x on 16-2-19.
 */
public abstract class VersionCheckLauncherActivity extends BaseCommonActivity implements VersionChecker.VersionCheckListener {

    private static final String USE_RECORD_SHARE_REFERENCES = "use.recor._share.references";

    private static final String KEY_IS_USE = "key_is_use";

    private static final String KEY_VERSION_CODE = "key_version_code";

    /**
     * 最小等待时间
     */
    private static final long MIN_WAIT_TIME = 5000;

    /**
     * 逻辑处理完成，进入app的handler what值
     */
    private static final int HANDLER_WHAT_ENTER = 0x23;

    /**
     * 版本检查失败，退出的handler what
     */
    private static final int HANDLER_WHAT_FINISH = 0x24;

    /**
     * 版本检查失败退出的延迟
     */
    private static final long EXIT_DELAY = 1000;

    /**
     * 进入的时间
     */
    private long entryTime;

    private Runnable VERSION_CHECK_RUNNABLE = new Runnable() {
        @Override
        public void run() {
            VersionChecker vc = VersionChecker.getInstance();
            vc.registerVersionCheckListener(VersionCheckLauncherActivity.this);
            vc.check(VersionCheckLauncherActivity.this.getApplicationContext(), getVersionCheckUrl());
        }
    };

    /**
     * handler
     */
    private BaseWeakHandler mHandler = new BaseWeakHandler<VersionCheckLauncherActivity>(this) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_WHAT_ENTER: {
                    long consumedTime = ((System.nanoTime() - entryTime) / 1000);
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            onEntry(isFirstUse());
                        }
                    }, Math.max(MIN_WAIT_TIME - consumedTime, 0));
                    break;
                }
                case HANDLER_WHAT_FINISH: {
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, EXIT_DELAY);
                    break;
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);

        entryTime = System.nanoTime();
        if (CommonApplication.getInstance().isInitialized()) {
            VERSION_CHECK_RUNNABLE.run();
        } else {
            CommonApplication.getInstance().setInitializeCallBack(new CommonApplication.InitializeCallBack() {
                @Override
                public void onInitialized(long howLong) {
                    CommonApplication.getInstance().setInitializeCallBack(null);
                    getHandler().post(VERSION_CHECK_RUNNABLE);
                }
            });
        }
    }


    /**
     * 是否强制进行版本检查
     * 如果强制版本检查：在无法连接到服务器时，不能进入Application
     * 如果不强制版本检查：在无法连接到服务器时，可以进入Application，
     * 但是如果服务端的配置文件中描述了需要强制更新，那么用户就必须先完成版本检查
     * 而且必须当前的客户端是最新版本才能进入Application
     *
     * @return true or false
     */
    public abstract boolean foreVersionCheck();

    /**
     * 获取版本检查的地址
     *
     * @return 服务器端配置文件地址
     */
    public abstract String getVersionCheckUrl();


    /**
     * 当这个界面的逻辑执行完成后调用
     *
     * @param isFirstEntry 是否是第一次进入
     */
    public abstract void onEntry(boolean isFirstEntry);

    /**
     * 是否是第一次使用
     *
     * @return true or false
     */
    private boolean isFirstUse() {
        boolean isFirst = false;

        SharedPreferences sp = null;
        int currentVersionCode = 0;
        try {
            sp = getSharedPreferences(USE_RECORD_SHARE_REFERENCES, Context.MODE_PRIVATE);
            boolean oldVersionIsUse = sp.getBoolean(KEY_IS_USE, false);
            int oldVersionCode = sp.getInt(KEY_VERSION_CODE, 1);
            currentVersionCode = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;
            //如果新版本和当前版本不同，那么就是第一次使用
            if (oldVersionCode != currentVersionCode) {
                //first use
                isFirst = true;
            } else {
                //如果两个版本相同，那么看下是否使用过
                if (!oldVersionIsUse) {
                    isFirst = true;
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            if (Config.DEBUG) {
                ALog.e(TAG, e);
            }
        }

        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(KEY_IS_USE, true);
        editor.putInt(KEY_VERSION_CODE, currentVersionCode);
        editor.commit();
        return isFirst;
    }

    @Override
    public void onUpdateDialogDismissed(VersionChecker vc, Version remoteVersion) {
        vc.unregisterVersionCheckListener(this);
        if (remoteVersion != null && !remoteVersion.isForceUpdate()) {
            mHandler.sendEmptyMessage(HANDLER_WHAT_ENTER);
        }
    }

    @Override
    public void onLatestVersion(VersionChecker vc, Version locVersion, Version remoteVersion) {
        //Already latest version,send message to handler.
        vc.unregisterVersionCheckListener(this);
        mHandler.sendEmptyMessage(HANDLER_WHAT_ENTER);
    }

    @Override
    public void onNewVersionFound(VersionChecker vc, Version locVersion, Version remoteVersion, boolean forceUpdate) {

        //If don't need force update ,send message to handler.

    }

    @Override
    public void onVersionCheckFailure(VersionChecker vc, Exception e) {
        vc.unregisterVersionCheckListener(this);
        if (foreVersionCheck()) {
            showToast(R.string.connect_failure_exit_application);
            mHandler.sendEmptyMessage(HANDLER_WHAT_FINISH);
        } else {
            mHandler.sendEmptyMessage(HANDLER_WHAT_ENTER);
        }
    }

    @Override
    public void applyTranslationStatusBarAndNavigationBar(Tint tint) {

    }
}
